/**
 * 
 */

var geocoder;
var map;
var marker01;
var marker02;
var callAutocompleteEvent = true;

String.prototype.splice = function( idx, rem, s ) {
    return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};


function getNeighborhood(gmapsAddress){
	  var neighborhood = gmapsAddress.substr(gmapsAddress.indexOf(' - ') + 2);
	  neighborhood = neighborhood.substr(0, neighborhood.indexOf(','));
	  return neighborhood;
	  
}
  
 function createResumedAddress(description, neighborhood ){
	  var endCityIndex = description.lastIndexOf(" - ");
	  var descricaoNoState = description.substr(0, endCityIndex );
	  var commaIndex = descricaoNoState.lastIndexOf(', ');
	  
	  
	  resumedAddress = description.splice(commaIndex + 1, 0, neighborhood + ',');
	  var lastCommaIndex = resumedAddress.lastIndexOf(',');
	  resumedAddress = resumedAddress.substring(0, lastCommaIndex);
	  return resumedAddress;
 }
 
 function unlockEvent(){
	 if(callAutocompleteEvent == true){
		   callAutocompleteEvent = false; 
	  }
	  else{
	       return;
	 }
 }
  
function lockEvent(){
	callAutocompleteEvent = true;
}
 
  
      originResult = null;
      destinyResult = null;
  function initialize() {
	  	
	    
	  geocoder = new google.maps.Geocoder(); 
	  var latlng = new google.maps.LatLng(-7.151482,-34.834385);

	  var myOptions = {
	      zoom: 13,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	    
	    var input = document.getElementById('origem-descricao');
		autocomplete = new google.maps.places.Autocomplete(input, { componentRestrictions: {country: 'br'} });
		autocomplete.bindTo('bounds', map);
		
		 var inputDestiny = document.getElementById('destino-descricao');
	     autocompleteDestiny = new google.maps.places.Autocomplete(inputDestiny, { componentRestrictions: {country: 'br'} });
	     autocompleteDestiny.bindTo('bounds', map);
		
		
	   marker01 = new google.maps.Marker({
	        position: latlng, 
	        animation: google.maps.Animation.DROP,
	        map: map,
	        title:"Origem"
	    });
	    google.maps.event.addListener(marker01, 'click', function() {
	      map.setZoom(15);
	    });
	    
	    
	    marker02 = new google.maps.Marker({
	        position: latlng, 
	        animation: google.maps.Animation.DROP,
	        map: map,
	        title:"Destino"
	    });
	    
	    var directionsRenderer = new google.maps.DirectionsRenderer();
	    directionsRenderer.setMap(map);    
	    
	    var directionsService = new google.maps.DirectionsService();
	    
	    
	    //----------- Events -------------------------
	    google.maps.event.addListener(marker02, 'click', function() {
	      map.setZoom(15);
	    });
	    
	   google.maps.event.addListener(autocomplete, 'place_changed', function() {
		  unlockEvent();		
		  handleAutocomplete(autocomplete, autocompleteDestiny);
		  var place = autocomplete.getPlace();
		  if ( place.geometry.viewport) {
	  	      map.fitBounds( place.geometry.viewport);
	  	  } else {
	  	     map.setCenter(place.geometry.location);
	  	    
	  	  }
	      
	  	  marker01.setPosition( place.geometry.location);
	  	  $("#origem-latitude").val( place.geometry.location.lat());
	  	  $("#origem-longitude").val(place.geometry.location.lng());
	  	  
	  	  lockEvent();
	  	});
	   
	   google.maps.event.addListener(autocompleteDestiny, 'place_changed', function() {
		      unlockEvent();
		      handleAutocomplete(autocomplete, autocompleteDestiny);
		      var place = autocompleteDestiny.getPlace();
		      if (place.geometry.viewport) {
		  	      map.fitBounds(place.geometry.viewport);
		  	  } else {
		  	     map.setCenter(place.geometry.location);
		  	    
		  	  }
		      
		  	  marker02.setPosition(place.geometry.location);
		  	  $("#destino-latitude").val(place.geometry.location.lat());
		  	  $("#destino-longitude").val(place.geometry.location.lng());
		  	  lockEvent();
		  	});
	   
	   
	   function handleAutocomplete(autocomplete, autocompleteDestiny, placeViewport){
		      var place = autocomplete.getPlace();
		  	  var placeDestiny = autocompleteDestiny.getPlace();
		  	  if(!place){
				  place = originResult;
			  }
			  if(!placeDestiny){
				  placeDestiny = destinyResult;
			  }
		  	  if (place && placeDestiny){
		  		var request = {
		  		      origin: place.geometry.location.lat()+','+ place.geometry.location.lng(), 
		  		      destination: placeDestiny.geometry.location.lat()+','+ placeDestiny.geometry.location.lng(),
		  		      travelMode: google.maps.DirectionsTravelMode.DRIVING,
		  		      unitSystem: google.maps.DirectionsUnitSystem.METRIC
		  		    };
		  		
		  		directionsService.route(request, function(response, status) {
		  			if (status == google.maps.DirectionsStatus.OK) {
			  			  var startAddress = response.routes[0].legs[0].start_address;
			  			  var endAddress = response.routes[0].legs[0].end_address;
			  			  var startNeighborhood = getNeighborhood(startAddress);
			  			  var endNeighborhood = getNeighborhood(endAddress);
			  			  var polyline = response.routes[0].overview_polyline.points;
			  			  
			  		      directionsRenderer.setDirections(response);
			  		      $("#origem-bairro").val(startNeighborhood);
			  		      $("#destino-bairro").val(endNeighborhood);
			  		      $("#origem-exibicao").val(createResumedAddress(($('#origem-descricao').val()), startNeighborhood));
			  		      $("#destino-exibicao").val(createResumedAddress(($('#destino-descricao').val()), endNeighborhood));
			  		      
			  		      $("#carona-polyline").val(polyline);
			  		      
			  		      $("#distance-value").text(response.routes[0].legs[0].distance.text);
			  		      $("#duration-value").text(response.routes[0].legs[0].duration.text);
			  		  } else {
		  		    alert('Error: ' + status);
		  		  }
		  		});
		  	  }
		  	  
	   }
	    
     
  }
  
  google.maps.event.addDomListener(window, 'load', initialize);
  
  

   $(document).ready(function(){
	   	
	   //TODO retrabalhar pra evitar chamadas desnecessárias.
	   function selectFirstResult(jqInput, index) {
		   
	        $(".pac-container:eq("+index+")").hide();
	        var firstResult = $(".pac-container:eq("+index+") .pac-item:first").text();
	       
	        geocoder.geocode({"address":firstResult }, function(results, status) {
	            if (status == google.maps.GeocoderStatus.OK) {
	                var lat = results[0].geometry.location.lat(),
	                lng = results[0].geometry.location.lng(),
	                placeName = results[0].address_components[0].long_name,
	                latlng = new google.maps.LatLng(lat, lng);
	                jqInput.val(firstResult);
	                if(index == 0){
		                originResult = results[0];
	                }
	                else{
		                destinyResult = results[0];
	                }
	                autocompleteTrigger = index == 0 ? autocomplete : autocompleteDestiny;
	                setTimeout('', 300);
		            google.maps.event.trigger(autocompleteTrigger, 'place_changed');
		            
		            
	            }
	        });   
	    }
	   
	   function mouseoutBeforeCompleteHandle(jqInput, index){
		    
	       if(!$(".pac-container:eq("+index+")").is(":hover")){
	    	        
	            	selectFirstResult(jqInput, index);
	        }
	        
	    }
	  
	   
	   $("#origem-descricao").focusout(function () { 
           mouseoutBeforeCompleteHandle($(this), 0);  
           
       });
	   
	   
	   $("#destino-descricao").focusout(function () {
           mouseoutBeforeCompleteHandle($(this), 1);      
           
           
	   });
	   
	   var dateToday = new Date();
	   $("#carona-data").datetimepicker({minDate: dateToday, hourGrid:3, minuteGrid:10, dateFormat: 'dd/mm/yy', timeFormat:"hh:mm", changeMonth: true, changeYear: true });
	   
	   $('#carona-form').validate(
			   {
				   rules: {
				   "carona.origem.descricao": {
				       required: true
				   },
				   "carona.destino.descricao": {
				       required: true,
				  
				   },
				   "carona.data": {				   
				       required: true
				   }				  
				   },
				   messages: {
					"carona.origem.descricao": {
				        required: "Escolha um endereço de origem"
				     },
				    "carona.destino.descricao": {
					    required: "Escolha um endereço de destino"
					   },
				     "carona.data": {				   
				       required: "Defina a data da carona"
				     } 
				   },
				   highlight: function(label) {
				   $(label).closest('.control-group').addClass('error');
				   },
				   success: function(label) {
				   label
				   .text('OK!').addClass('valid')
				   .closest('.control-group').addClass('success');
				   }
				   });
  });
		
  